<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="90px"
    >
      <el-form-item label="销售单号" prop="no">
        <el-input
          v-model="queryParams.no"
          placeholder="请输入销售单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="产品" prop="productId">
        <el-select
          v-model="queryParams.productId"
          clearable
          filterable
          placeholder="请选择产品"
          class="!w-240px"
        >
          <el-option
            v-for="item in productList"
            :key="item.id"
            :label="item.itemName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间" prop="orderTime">
        <el-date-picker
          v-model="queryParams.orderTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="客户" prop="customerId">
        <el-select
          v-model="queryParams.customerList"
          clearable
          filterable
          placeholder="请选择客户"
          class="!w-240px"
        >
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销售状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable class="!w-240px">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:sale-order:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:sale-order:export']"
        >
          <Icon icon="ep:upload" />导出
        </el-button>
        <el-button size="default" @click="handleImport">
          <Icon icon="ep:download" class="mr-5px" /> 导入
        </el-button>
        <el-button
          type="danger"
          plain
          @click="handleDelete(selectionList.map((item) => item.id))"
          v-hasPermi="['erp:sale-order:delete']"
          :disabled="selectionList.length === 0"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 删除
        </el-button>
        <el-button
          type="primary"
          plain
          @click="generateInvoice"
          v-hasPermi="['erp:sale-order:delete']"
          :disabled="selectionList.length === 0"
        >
          生成发票
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-row :gutter="10" class="flex-justify-between w-full" style="margin-bottom: 16px">
      <div class="flex">
        <el-col :span="1.5">
          <div>
            <el-button
              type="default"
              plain
              @click="openForm('update')"
              :disabled="selectionList.length !== 1"
              v-hasPermi="['system:tenant:export']"
            >
              修改单据信息
            </el-button>
          </div>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="default"
            plain
            @click="handleSubmit"
            v-hasPermi="['system:tenant:export']"
            :disabled="selectionList.length !== 1"
          >
            提交
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="default"
            plain
            @click="handleAudit"
            v-hasPermi="['system:tenant:export']"
            :disabled="selectionList.length !== 1"
          >
            审核
          </el-button>
        </el-col>
      </div>
      <div class="flex items-center">
        <el-col :span="10.1">
          <div style="text-align: right">
            <el-button type="default" plain @click="btnLie">
              <img key="1" alt="" width="25px" height="20px" src="@/assets/svgs/column.svg" />
              列表字段
            </el-button>
          </div>
        </el-col>
      </div>
    </el-row>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      show-summary
      :summary-method="getSummaries"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column width="60" label="选择" type="selection" />
      <!-- <el-table-column label="编号" align="center" prop="id" width="140" /> -->
      <!-- <el-table-column label="销售单编号" align="center" prop="no" width="160" /> -->
      <el-table-column label="销售状态" align="center" v-if="visibleColumns.status" prop="status" width="160">
        <template #default="scope">
          {{ getStatusText(scope.row.status) }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="客户编号" align="center" prop="customerId" width="160" />
      <el-table-column label="结算账户编号" align="center" prop="accountId" width="160" />
      <el-table-column label="销售用户编号" align="center" prop="saleUserId" width="160" /> -->
      <el-table-column
        label="下单时间"
        align="center"
        prop="orderTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="合计数量" v-if="visibleColumns.totalCount" align="center" prop="totalCount" width="160" />
      <el-table-column label="合计价格，单位：元" v-if="visibleColumns.totalPrice" align="center" prop="totalPrice" width="160" />
      <el-table-column
        label="合计产品价格，单位：元"
        align="center"
        prop="totalProductPrice"
        width="160"
      />
      <el-table-column label="合计税额，单位：元" v-if="visibleColumns.totalTaxPrice" align="center" prop="totalTaxPrice" width="160" />
      <el-table-column label="优惠率，百分比" v-if="visibleColumns.discountPercent" align="center" prop="discountPercent" width="160" />
      <el-table-column label="优惠金额，单位：元" v-if="visibleColumns.discountPrice" align="center" prop="discountPrice" width="160" />
      <el-table-column label="定金金额，单位：元" v-if="visibleColumns.depositPrice" align="center" prop="depositPrice" width="160" />
      <el-table-column label="附件地址" align="center" v-if="visibleColumns.fileUrl" prop="fileUrl" width="160" />
      <el-table-column label="备注" align="center" v-if="visibleColumns.remark" prop="remark" width="160" />
      <el-table-column label="销售出库数量" v-if="visibleColumns.outCount" align="center" prop="outCount" width="160" />
      <el-table-column label="销售退货数量" align="center" prop="returnCount" width="160" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="库位" align="center" prop="warehouseLocationId" width="160" />
      <el-table-column label="仓库区域" align="center" prop="warehouseAreaId" width="160" />
      <el-table-column label="销售类型" align="center" prop="salesType" width="160" />
      <el-table-column label="单据状态" v-if="visibleColumns.documentStatus" align="center" prop="documentStatus" width="160" />
      <el-table-column label="客户名称" v-if="visibleColumns.customerName" align="center" prop="customerName" width="160" />
      <el-table-column label="出库状态" align="center" prop="outboundStatus" width="160" />
      <el-table-column label="本次定金" align="center" prop="currentDeposit" width="160" />
      <el-table-column label="本次定金比率" align="center" prop="currentDepositRatio" width="160" />
      <el-table-column
        label="本次定金状态"
        align="center"
        prop="currentDepositStatus"
        width="160"
      />
      <el-table-column label="累计预收" align="center" prop="accumulatedAdvance" width="160" />
      <el-table-column
        label="累计预收比例"
        align="center"
        prop="accumulatedAdvanceRatio"
        width="160"
      />
      <el-table-column label="送货状态" align="center" prop="deliveryStatus" width="160" />
      <el-table-column label="制单人" align="center" prop="documentMaker" />
      <el-table-column label="退货状态" align="center" prop="returnStatus" />
      <el-table-column label="整单折扣额" align="center" prop="orderDiscountAmount" width="160" />
      <el-table-column label="整单折扣率" align="center" prop="orderDiscountRate" width="160" />
      <el-table-column label="成交金额" align="center" prop="transactionAmount" />
      <el-table-column
        label="预计销售费用"
        align="center"
        prop="estimatedSalesExpense"
        width="160"
      />
      <el-table-column label="发票类型" align="center" prop="invoiceType" />
      <el-table-column label="已开票金额" align="center" prop="invoicedAmount" width="160" />
      <el-table-column label="未开票金额" align="center" prop="uninvoicedAmount" width="160" />
      <el-table-column label="销售专员" align="center" prop="salesSpecialist" />
      <el-table-column label="未出库数量" align="center" prop="undeliveredQuantity" width="160" />
      <el-table-column label="客户来源" align="center" prop="customerSource" />
      <el-table-column label="已退货数量" align="center" prop="returnedQuantity" width="160" />
      <el-table-column label="不含税金额" align="center" prop="amountWithoutTax" width="160" />
      <el-table-column label="含税金额" align="center" prop="amountWithTax" />
      <el-table-column label="开票状态" align="center" prop="invoicingStatus" />
      <el-table-column
        label="生产入库状态"
        align="center"
        prop="productionStorageStatus"
        width="160"
      />
      <el-table-column label="是否逾期" align="center" prop="isOverdue" />
      <el-table-column
        label="交货日期"
        align="center"
        prop="deliveryDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="客户订单编号" align="center" prop="customerOrderNo" />
      <el-table-column label="操作" align="center" fixed="right" width="300">
        <template #default="scope">
          <el-button
            link
            @click="openForm('detail', scope.row.id)"
            v-hasPermi="['erp:sale-order:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="print('', scope.row.id)"
            v-hasPermi="['erp:sale-order:update']"
          >
            打印
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('copy', scope.row.id)"
            v-hasPermi="['erp:sale-order:update']"
          >
            复制
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleSubmit('', scope.row.id)"
            v-hasPermi="['erp:sale-order:update']"
            :disabled="scope.row.status != 110"
          >
            手动完成
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <!-- 自定义字段 -->
  <el-dialog v-model="dialogVisible" title="自定义字段" width="50%" :before-close="handleClose">
    <div class="content">
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.status" label="销售状态" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.totalCount" label="合计数量" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.totalPrice" label="合计价格，单位：元" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.totalProductPrice" label="合计产品价格，单位：元" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.totalTaxPrice" label="合计税额，单位：元" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.discountPercent" label="优惠率，百分比" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.discountPrice" label="优惠金额，单位：元" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.depositPrice" label="定金金额，单位：元" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.fileUrl" label="附件地址" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.remark" label="备注" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.outCount" label="销售出库数量" size="large"
      /></div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 表单弹窗：添加/修改 -->
  <SaleOrderForm ref="formRef" @success="getList" />
  <CustomerImportForm ref="importFormRef" @success="getList" />
  <OrderForm ref="orderFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import SaleOrderForm from './SaleOrderForm.vue'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { UserVO } from '@/api/system/user'
import * as UserApi from '@/api/system/user'
import { erpCountTableColumnFormatter, erpPriceTableColumnFormatter } from '@/utils'
import { SaleOrderApi, SaleOrderVO } from '@/api/erp/sale/order'
import CustomerImportForm from '@/views/crm/customer/CustomerImportForm.vue'
import type { TableColumnCtx } from 'element-plus'
import { CustomerApi, CustomerVO } from '@/api/erp/sale/customer'
import { StockApi, DictItemConfigVO } from '@/api/erp/stock/stock'
import OrderForm from './components/orderForm.vue'
/** ERP 销售订单列表 */
defineOptions({ name: 'ErpSaleOrder' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<SaleOrderVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined,
  customerId: undefined,
  productId: undefined,
  orderTime: [],
  status: undefined
})
const queryProductParams = reactive({
  pageNo: 1,
  pageSize: 10,
  itemType: 1
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const productList = ref<any>([]) // 产品列表
const customerList = ref<CustomerVO[]>([]) // 客户列表
const userList = ref<UserVO[]>([]) // 用户列表
const order = ref(false)
const statusMap: Record<number, string> = {
  10: '未审核',
  20: '待拟合同',
  30: '合同待审核',
  40: '待生产',
  50: '生产中',
  60: '生产完成',
  70: '待出库',
  80: '已出库',
  90: '待退回',
  100: '已退回',
  110: '未完成'
}
const statusOptions = ref([
  { value: 10, label: '未审核' },
  { value: 20, label: '待拟合同' },
  { value: 30, label: '合同待审核' },
  { value: 40, label: '待生产' },
  { value: 50, label: '生产中' },
  { value: 60, label: '生产完成' },
  { value: 70, label: '待出库' },
  { value: 80, label: '已出库' },
  { value: 90, label: '待退回' },
  { value: 100, label: '已退回' },
  { value: 110, label: '未完成' }
])
// 状态值转换为文本的方法
const getStatusText = (status: number) => {
  return statusMap[status] || '--'
}
interface Product {
  totalCount: number
  totalPrice: number
  count: number
  outCount: number
  returnCount: number
  currentDeposit: number
  transactionAmount: number
  invoicedAmount: number
  uninvoicedAmount: number
  amountWithoutTax: number
  amountWithTax: number
}
const SUMMARY_FIELDS = [
  'totalCount',
  'totalPrice',
  'count',
  'outCount',
  'returnCount',
  'currentDeposit',
  'transactionAmount',
  'invoicedAmount',
  'uninvoicedAmount',
  'amountWithoutTax',
  'amountWithTax'
]

const outStatusOption = ref<{ value: string; label: string }[]>([])
const reftunStatusOption = ref<{ value: string; label: string }[]>([])

const getSummaries = (param: { columns: TableColumnCtx<Product>[]; data: Product[] }) => {
  const sums: (string | VNode)[] = []

  param.columns.forEach((column, index) => {
    if (index === 0) {
      // 第一列显示"合计"
      sums[index] = h('div', { style: { textDecoration: 'none' } }, ['合计'])
      return
    }

    const property = column.property

    // 只对指定的字段进行合计
    if (SUMMARY_FIELDS.includes(property)) {
      const values = param.data.map((item) => Number(item[property]) || 0)
      const sum = values.reduce((acc, curr) => acc + curr, 0)

      sums[index] = String(sum)
    } else {
      sums[index] = ''
    }
  })

  return sums
}
const visibleColumns = ref({
  no: true,
  status: true,
  materialCategory: true,
  spec: true,
  inventoryArea: true,
  location: true,
  model: true,
  loBatchNumber: true,
  inventoryStatus: true,
  materialStatus: true,
  areaStatus: true,
  selection: true,
  customerId: true,
  customerName: true,
  accountId: true,
  saleUserId: true,
  orderTime: true,
  totalCount: true,
  totalPrice: true,
  totalProductPrice: true,
  totalTaxPrice: true,
  discountPrice: true,
  depositPrice: true,
  productId: true,
  productPrice: true,
  count: true,
  productNames: true,
  outCount: true,
  returnCount: true,
  salesType: true,
  documentStatus: true,
  outboundStatus: true,
  currentDeposit: true,
  currentDepositRatio: true,
  currentDepositStatus: true,
  accumulatedAdvance: true,
  accumulatedAdvanceRatio: true,
  deliveryStatus: true,
  documentMaker: true,
  returnStatus: true,
  orderDiscountAmount: true,
  orderDiscountRate: true,
  transactionAmount: true,
  estimatedSalesExpense: true,
  invoiceType: true,
  invoicedAmount: true,
  uninvoicedAmount: true,
  salesSpecialist: true,
  undeliveredQuantity: true,
  customerSource: true,
  returnedQuantity: true,
  amountWithoutTax: true,
  amountWithTax: true,
  invoicingStatus: true,
  productionStorageStatus: true,
  isOverdue: true,
  deliveryDate: true,
  customerOrderNo: true,
  creator: true,
  creatorName: true,
  createTime: true
})

const handleSubmit = async () => {
  if (selectionList.value.length !== 1) {
    message.error('请选择一条数据进行提交')
    return
  }
  try {
    const id = selectionList.value[0].id
    const data = {
      status: 1,
      id: id
    }
    await SaleOrderApi.saleOrderComplete(data)
    message.success('提交成功')
    await getList()
  } catch (error) {
    console.error('提交失败：', error)
  }
}
const handleAudit = async () => {
  if (selectionList.value.length !== 1) {
    message.error('请选择一条数据进行审核')
    return
  }
  try {
    const id = selectionList.value[0].id
    const data = {
      status: 1,
      id: id
    }
    await SaleOrderApi.saleOrderAudit(data)
    message.success('提交成功')
    await getList()
  } catch (error) {
    console.error('提交失败：', error)
  }
}
const tempVisibleColumns = ref({ ...visibleColumns.value })
const dialogVisible = ref(false)
const btnLie = () => {
  tempVisibleColumns.value = { ...visibleColumns.value }
  dialogVisible.value = true
}
/** 导入按钮操作 */
const importFormRef = ref<InstanceType<typeof CustomerImportForm>>()
const handleImport = () => {
  importFormRef.value?.open()
}

// 列表字段确认选择
const handleConfirm = () => {
  visibleColumns.value = { ...tempVisibleColumns.value }
  dialogVisible.value = false
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await SaleOrderApi.getSaleOrderPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
  if (type === 'updata') {
    const id = selectionList.value[0].id
    formRef.value.open(type, id)
  }
}

// 打开修改编辑
const orderFormRef = ref()
const edit = () => {
  const id = selectionList.value[0].id
  orderFormRef.value.open(id)
}
/** 删除按钮操作 */
const handleDelete = async (ids: number[]) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SaleOrderApi.deleteSaleOrder(ids)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
    selectionList.value = selectionList.value.filter((item) => !ids.includes(item.id))
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SaleOrderApi.exportSaleOrder(queryParams)
    download.excel(data, '销售订单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 选中操作 */
const selectionList = ref<SaleOrderVO[]>([])
const handleSelectionChange = (rows: SaleOrderVO[]) => {
  selectionList.value = rows
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 加载产品、仓库列表、客户
  // productList.value = await ProductApi.getProductSimpleList()
  // customerList.value = await CustomerApi.getCustomerSimpleList()
  userList.value = await UserApi.getSimpleUserList()
  const outStatus = { dictCode: 'out_status' }
  const statusRes = await StockApi.getByDictCode(outStatus)
  outStatusOption.value = statusRes.map((item) => ({
    value: item.value,
    label: item.description
  }))
  const returnStatus = { dictCode: 'return_status' }
  const returnStatusRes = await StockApi.getByDictCode(returnStatus)
  reftunStatusOption.value = returnStatusRes.map((item) => ({
    value: item.value,
    label: item.description
  }))
  productList.value = (await StockApi.getMartaialPage(queryProductParams)).list
  customerList.value = (await CustomerApi.getCustomerPage(queryParams)).list
})
</script>
